package com.steveproject.parttimeworktree.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.steveproject.parttimeworktree.App;
import com.steveproject.parttimeworktree.R;
import com.steveproject.parttimeworktree.adapter.Part2JobAdapter;
import com.steveproject.parttimeworktree.adapter.PartBannerEntity;
import com.steveproject.parttimeworktree.base.BaseFragment;
import com.steveproject.parttimeworktree.entity.BannerEntity;
import com.steveproject.parttimeworktree.entity.Part2JobEntity;
import com.steveproject.parttimeworktree.entity.PartBaseEntity;
import com.steveproject.parttimeworktree.loader.GlideImageLoader;
import com.steveproject.parttimeworktree.myinterface.DeleteJobs;
import com.steveproject.parttimeworktree.myinterface.myLocation;
import com.steveproject.parttimeworktree.net.MyCallback;
import com.steveproject.parttimeworktree.net.NoValidationTask;
import com.steveproject.parttimeworktree.net.Task;
import com.steveproject.parttimeworktree.ui.activity.Part2AddressActivity;
import com.steveproject.parttimeworktree.ui.activity.PartBannerDetailActivity;
import com.steveproject.parttimeworktree.ui.activity.PartDetailActivity;
import com.steveproject.parttimeworktree.ui.activity.PartSearchActivity;
import com.steveproject.parttimeworktree.utils.GPSUtils;
import com.steveproject.parttimeworktree.utils.SPUtils;
import com.steveproject.parttimeworktree.utils.ScreenUtil;
import com.steveproject.putorefresh.BaseBothListener;
import com.steveproject.putorefresh.PullToBothLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

import static android.support.v4.content.PermissionChecker.PERMISSION_GRANTED;

public class PopularPartTimeFragment extends BaseFragment {
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.mBanner)
    Banner mBanner;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToBothLayout;

    @BindView(R.id.tv_recommend)
    TextView recommend;
    @BindView(R.id.tv_high)
    TextView high;
    @BindView(R.id.tv_zc)
    TextView zc;
    @BindView(R.id.tv_address)
    TextView tvAddress;

    private boolean isFirst = true;
    private List<View> views;
    private Part2JobAdapter part2JobAdapter = null;
    private List<Part2JobEntity> list = new ArrayList<>();
    private List<PartBannerEntity> bannerEntities = new ArrayList<>();


    private int page = 1;
    private boolean isRefresh = true;
    private String type = "0";
    private String city = "北京市";

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String str) {
        //获取出价记录  然后进行设置
        try {
            //重新刷数据
            if ("changeRegion".equals(str)) {//传过来值
                if (!isFirst) {
                    String region = SPUtils.get(App.getContext(), "region", "") + "";
                    if (region.equals("")) {
                        tvAddress.setText("北京市");
                    } else {
                        tvAddress.setText(region);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取定位权限
     */
    private void getLocationPermission() {
        int flag = ActivityCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION);
        if (flag != PackageManager.PERMISSION_GRANTED) {
            PopularPartTimeFragment.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            getLocation();
        }
    }

    //获取位置信息
    private void getLocation() {
        //获取城市编码
        GPSUtils.getInstance(getActivity()).getLocation(new myLocation() {
            @Override
            public void onSuccess(String cc) {
                city = cc;
                //定位成功 开始进行赋值
                tvAddress.setText(city);
                SPUtils.put(App.getContext(), "region", cc);
            }

            @Override
            public void onFail(int code) {
                //获取位置信息失败
                tvAddress.setText(city);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PERMISSION_GRANTED) {//选择了“始终允许”
                    getLocation();
                } else {
                    //权限被拒绝
                    tvAddress.setText(city);
                }
            }
        }

    }

    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_part_home, null);
    }

    //设置banner图
    private void setBanner(List<BannerEntity> list) {
        List<String> url = new ArrayList<>();//图片url
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                url.add(list.get(i).getImgUrl());
            }
        }
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        GlideImageLoader glideImageLoader = new GlideImageLoader();
        //设置图片加载器
        mBanner.setImageLoader(glideImageLoader);
        //设置图片集合
        mBanner.setImages(url);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置动画
        mBanner.setBannerAnimation(Transformer.Default);
        //设置轮播时间
        mBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.start();
        mBanner.startAutoPlay();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                String action = bannerEntities.get(position).getAction();
                switch (action) {
                    case "0":
                        break;
                    case "1":
                        break;
                    case "2":
                        break;
                    case "3":
                        String url = bannerEntities.get(position).getToUrl();
                        Log.e("testUrl", "onItemClick: " + url);
                        startActivity(new Intent(getActivity(), PartBannerDetailActivity.class).putExtra("url", url));
                        break;
                }
            }
        });
    }

    @OnClick({R.id.tv_high, R.id.tv_zc, R.id.tv_recommend, R.id.ll_address, R.id.rel_search})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_high://高薪职位
                changeTV(R.id.tv_high);
                type = "1";
                isRefresh = true;
                loadJobs();
                break;
            case R.id.tv_zc://宝妈专场
                changeTV(R.id.tv_zc);
                type = "2";
                isRefresh = true;
                loadJobs();
                break;
            case R.id.tv_recommend://今日推荐
                changeTV(R.id.tv_recommend);
                type = "0";
                isRefresh = true;
                loadJobs();
                break;
            case R.id.ll_address://跳转地址选择
                startActivity(new Intent(getActivity(), Part2AddressActivity.class));
                break;
            case R.id.rel_search:
                startActivity(new Intent(getActivity(), PartSearchActivity.class));
                break;
        }
    }

    //更改背景和字体颜色
    private void changeTV(int id) {
        for (int i = 0; i < views.size(); i++) {
            if (views.get(i).getId() == id) {
                views.get(i).setBackgroundResource(R.drawable.part_home_menu_bg);
                ((TextView) views.get(i)).setTextColor(Objects.requireNonNull(getActivity()).getResources().getColor(R.color.whiteffffff));
            } else {
                views.get(i).setBackgroundResource(R.color.whiteffffff);
                ((TextView) views.get(i)).setTextColor(Objects.requireNonNull(getActivity()).getResources().getColor(R.color.color666));
            }
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        setListen();
        initRecycle();
        views = new ArrayList<>();
        views.add(recommend);
        views.add(high);
        views.add(zc);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirst) {
                isFirst = false;
                //初始化banner和recycleView组件
                getBanner();
                loadJobs();
                getLocationPermission();
            }
        }
    }


    //关闭下拉刷新和上拉加载
    private void closePullTo() {
        pullToBothLayout.finishRefresh();
        pullToBothLayout.finishLoadMore();
    }

    private void setListen() {
        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                page = 1;
                isRefresh = true;
                loadJobs();
            }

            @Override
            public void loadMore() {
                page++;
                isRefresh = false;
                loadJobs();
            }
        });
    }

    //获取职位列表
    private void loadJobs() {
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        NoValidationTask.getApiService().getHomeJobs(userId, page, type).enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (jsonArray.size() > 0) {
                    if (isRefresh) {
                        list.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Part2JobEntity part2JobEntity = new Part2JobEntity();
                            part2JobEntity.setEducation(jsonArray.getJSONObject(i).getString("eduRequire"));
                            part2JobEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            part2JobEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            part2JobEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            part2JobEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            part2JobEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            part2JobEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            part2JobEntity.setYear(jsonArray.getJSONObject(i).getString("expRequire"));
                            list.add(part2JobEntity);
                        }

                    } else {//上拉加载
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Part2JobEntity part2JobEntity = new Part2JobEntity();
                            part2JobEntity.setEducation(jsonArray.getJSONObject(i).getString("eduRequire"));
                            part2JobEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            part2JobEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            part2JobEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            part2JobEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            part2JobEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            part2JobEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            part2JobEntity.setYear(jsonArray.getJSONObject(i).getString("expRequire"));
                            list.add(part2JobEntity);
                        }
                    }
                } else {
                    if (isRefresh) {
                        list.clear();
                    }
                }
                part2JobAdapter.notifyDataSetChanged();
                closePullTo();
            }

            @Override
            protected void onFailure(Throwable t) {
                closePullTo();
            }
        });

    }

    //删除对应的的职位
    private void deleteJobs(String jobId, int position) {
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        Task.getApiService().deleteJob(userId, jobId).enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                list.remove(position);
                part2JobAdapter.notifyDataSetChanged();
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //初始化列表
    private void initRecycle() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        if (part2JobAdapter == null) {
            part2JobAdapter = new Part2JobAdapter(getActivity(), list, new DeleteJobs() {
                @Override
                public void delete(int position) {
                    deleteJobs(list.get(position).getJobId(), position);
                }
            });
        }
        part2JobAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getActivity(), PartDetailActivity.class).putExtra("jobId", list.get(position).getJobId()));
            }
        });
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(part2JobAdapter);
    }

    //获取banner
    private void getBanner() {
        NoValidationTask.getApiService().getHomeBanner().enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        PartBannerEntity partBannerEntity = new PartBannerEntity();
                        partBannerEntity.setAction(jsonArray.getJSONObject(i).getInteger("action") + "");
                        partBannerEntity.setBannerUrl(jsonArray.getJSONObject(i).getString("url"));
                        partBannerEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                        partBannerEntity.setToUrl(jsonArray.getJSONObject(i).getString("fileUrl"));
                        bannerEntities.add(partBannerEntity);
                    }
                    List<BannerEntity> list = new ArrayList<>();
                    for (int i = 0; i < bannerEntities.size(); i++) {
                        BannerEntity beanXBanner = new BannerEntity();
                        beanXBanner.setImgUrl(bannerEntities.get(i).getBannerUrl());
                        list.add(beanXBanner);
                    }
                    //刷新数据之后，需要重新设置是否支持自动轮播
                    setBanner(list);
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }
}
